#!/bin/bash

echo "🚀 启动少儿英语平台集群..."

# 检查 Redis
echo "📦 检查 Redis 服务..."
if ! redis-cli ping > /dev/null 2>&1; then
    echo "❌ Redis 未运行，请先启动 Redis"
    echo "💡 启动命令: redis-server"
    exit 1
fi
echo "✅ Redis 连接正常"

# 编译项目
echo "🔨 编译项目..."
mvn clean package -DskipTests

if [ $? -ne 0 ]; then
    echo "❌ 项目编译失败"
    exit 1
fi
echo "✅ 项目编译成功"

# 启动三个 Tomcat 实例
echo "🐱 启动 Tomcat 集群节点..."

# 节点1
echo "启动节点1 (端口 8080)..."
INSTANCE_ID=node1 java -jar target/child-english-platform-1.0.0.jar --server.port=8080 > logs/node1.log 2>&1 &
NODE1_PID=$!
echo $NODE1_PID > pids/node1.pid

# 节点2
echo "启动节点2 (端口 8081)..."
INSTANCE_ID=node2 java -jar target/child-english-platform-1.0.0.jar --server.port=8081 > logs/node2.log 2>&1 &
NODE2_PID=$!
echo $NODE2_PID > pids/node2.pid

# 节点3
echo "启动节点3 (端口 8082)..."
INSTANCE_ID=node3 java -jar target/child-english-platform-1.0.0.jar --server.port=8082 > logs/node3.log 2>&1 &
NODE3_PID=$!
echo $NODE3_PID > pids/node3.pid

# 创建必要的目录
mkdir -p logs
mkdir -p pids

# 等待应用启动
echo "⏳ 等待应用启动..."
sleep 15

# 检查节点状态
echo "🔍 检查节点状态..."
for port in 8080 8081 8082; do
    if curl -s http://localhost:$port/health > /dev/null; then
        echo "✅ 节点 $port 启动成功"
    else
        echo "❌ 节点 $port 启动失败"
    fi
done

# 启动 Nginx
echo "🔀 启动 Nginx 负载均衡器..."
nginx -c $(pwd)/nginx/nginx-cluster.conf

if [ $? -eq 0 ]; then
    echo "✅ Nginx 启动成功"
else
    echo "❌ Nginx 启动失败"
fi

echo ""
echo "=========================================="
echo "✅ 集群启动完成!"
echo "🌐 访问地址: http://localhost"
echo "📊 集群监控: http://localhost/cluster/health"
echo "🔍 节点健康检查:"
echo "   - 节点1: http://localhost:8080/cluster/health"
echo "   - 节点2: http://localhost:8081/cluster/health"
echo "   - 节点3: http://localhost:8082/cluster/health"
echo "📝 查看日志: tail -f logs/node*.log"
echo "=========================================="